package com.xuge.common.intercept;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 攔截器
 */
@Component
public class LoginIntercept implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判斷是否存在token信息
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
             token =  request.getParameter("token");
        }
        if (StringUtils.isEmpty(token)){
            response.getOutputStream().write("獲取token失敗".getBytes());
            return false;
        }
        //獲取用戶的id
        String userId = request.getHeader("userId");
        if (StringUtils.isEmpty(userId)){
            userId = request.getParameter("userId");
        }
        if (StringUtils.isEmpty(userId)){
            response.getOutputStream().write("用戶信息獲取失敗".getBytes());
            return false;
        }
        //根據用戶id 判斷token正確性
        Object o = redisTemplate.opsForValue().get(userId);
        if (!token.equals(o.toString())){
            response.getOutputStream().write("token信息有誤".getBytes());
            return false;
        }
        //設置token到request中
        request.setAttribute("token",token);
        return true;
    }
}
